package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"net/http"
	"path/filepath"
	"simple-app/lib/http_utils"
	"simple-app/lib/id"
	"simple-app/modules/service"
	"simple-app/structs/dto"
	"simple-app/structs/enum"
	"strings"
)

type userApi struct {
}

var UserApi = new(userApi)

func (a userApi) Login(c *gin.Context) {
	var in dto.LoginAccount
	if err := c.ShouldBindJSON(&in); err != nil {
		log.Error(err)
		http_utils.BadWithParamsError(c)
		return
	}
	if !service.UserService.VerifyCode(in.VeryCode) {
		http_utils.BadWithCode(c, enum.ErrorMap.VerifyCodeErr)
		return
	}
	result, _, err := service.UserService.UserLogin(in)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"success": false, "data": err.Error()})
		return
	}
	http_utils.Ok(c, gin.H{"success": true, "data": result})
}

func (a userApi) Register(c *gin.Context) {
	var in dto.UserRegister
	if err := c.ShouldBindJSON(&in); err != nil {
		log.Error(err)
		http_utils.BadWithParamsError(c)
		return
	}
	if err := service.UserService.Register(in); err != nil {
		log.Error(err)
		http_utils.BadWithErrMsg(c, err)
		return
	}
	http_utils.OK204(c)
}

func (a userApi) UploadImg(c *gin.Context) {
	f, err := c.FormFile("file")
	if err != nil {
		http_utils.BadWithParamsError(c)
		return
	}
	suf := f.Filename[strings.LastIndex(f.Filename, "."):]
	filename := fmt.Sprintf("%d%s", id.GetSnowId(), suf)
	err = c.SaveUploadedFile(f, filepath.Join(enum.ImagePath, filename))
	if err != nil {
		http_utils.BadWithErrMsg(c, err)
		return
	}
	http_utils.Ok(c, filename)
}
